package com.itheima.dao;

import com.itheima.bean.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class Student_test{
@Test
    public void test()throws Exception{//查询所有
    InputStream is = Resources.getResourceAsStream("mybatisconfig/MyBatisConfig");//加载核心配置文件
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);//获取sql会话工厂对象:这里对核心配置进行解析(构建者模式)
    SqlSession sqlSession = sqlSessionFactory.openSession();
    List<Student> list = sqlSession.selectList("StudentMapper.selectAll");
    for (Student student : list) {
        System.out.println(student);
    }
}
@Test
public  void selectById() throws Exception{//根据id查
    InputStream is = Resources.getResourceAsStream("mybatisconfig/MyBatisConfig");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    Student stu = sqlSession.selectOne("StudentMapper.selectById","1");
    System.out.println(stu);
    sqlSession.close();
}
@Test
    public void insert() throws Exception{
    InputStream is = Resources.getResourceAsStream("mybatisconfig/MyBatisConfig");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    Date date = new Date();
    Student student = new Student("3","死俊标的",18,date);
    int i = sqlSession.update("StudentMapper.insert",student);
    System.out.println(i);
    sqlSession.commit();
    is.close();
    sqlSession.close();
}
@Test
public void update() throws Exception {
    InputStream is = Resources.getResourceAsStream("mybatisconfig/MyBatisConfig");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    Date date = new Date();
    Student student = new Student("3","哒哒",99,date);
    int i = sqlSession.update("StudentMapper.update", student);
    System.out.println(i);
    sqlSession.commit();
    is.close();
    sqlSession.close();
}
@Test
public void delete() throws Exception{
    InputStream is = Resources.getResourceAsStream("mybatisconfig/MyBatisConfig");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    int i = sqlSession.update("StudentMapper.delete", "3");
    System.out.println(i);
    sqlSession.commit();
    is.close();
    sqlSession.close();
}
}
